<?php
class PdoDbEngine {
    private $conn;
    
    public function __construct() {
    }
    
    public function delete($sql) {
        return $this->conn->exec($sql); //todo delete 是幂等的？
    }
    
    public function connect($db_conf) {
        switch($db_conf['db_product']) {
            case 'mysql' :
                $dsn = 'mysql:';
                if(!empty($db_conf['unix_domain_socket'])) {
                    $dsn .= 'unix_socket=' . $db_conf['unix_domain_socket'] . ';';
                } else {
                    $dsn .= 'host=' . $db_conf['host'] . ';';
                }
                $dsn .= 'dbname=' . $db_conf['db_name'];
                $this->conn = new PDO($dsn, $db_conf['username'], $db_conf['password']);
                break;
            case 'pgsql' :
                $dsn = 'pgsql:host=' . $db_conf['host'] . ';port=' . $db_conf['port'] . ';dbname=' . $db_conf['db_name'] . ';user=' . $db_conf['username'] . ';password=' . $db_conf['password'];
                $this->conn = new PDO($dsn);
                break;
        }
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $this->conn; //todo throw
    }
    
    public function insertRow($sql)
    {
        $r = $this->conn->exec($sql);
        return $this->conn->lastInsertId();
    }
    
    public function insertRows($sql)
    {
        return $this->conn->exec($sql);
    }

    public function query($sql)
    {
        $r = $this->conn->query($sql);
        if(empty($r)) {
            return array();
        }
        $r->setFetchMode(PDO::FETCH_ASSOC);
        return $r->fetchAll();
    }

    public function selectCount($sql)
    {
        $r = $this->conn->query($sql);
        return intval($r->fetchColumn());
        /*if(empty($group_by)) {
            return $r->fetchColumn();
        }
        else {
            return $r->fetchAll();
        }*/
    }
    
    public function selectRow($sql)
    {
        $r = $this->selectRows($sql);
        return empty($r) ? array() : $r[0];
    }
    
    public function selectRows($sql)
    {
        $r = $this->conn->query($sql);
        $r->setFetchMode(PDO::FETCH_ASSOC);
        return $r->fetchAll();
    }
    
    public function update($sql)
    {
        return $this->conn->exec($sql);
    }
}
?>
